//
//  NSConversationViewController.m
//  Meboo
//
//  Created by kyo on 2023/10/18.
//

#import "NSConversationViewController.h"
#import "NSConversitionNavView.h"
#import "ChatSelectImageViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "MBChatPreviewVideoViewController.h"
#import "MBThumbnailCache.h"
#import "IQKeyboardManager.h"
#import "NSPhotoViewController.h"
#import "NSModelDetailViewController.h"
#import "NSMatchHeaderView.h"
#import "NSModelHotView.h"
#import "RCSightMessageCell.h"
#import "FXBlurView.h"
#import <RongIMLib/RCIMClient.h>
//#import "YBIBVideoData.h"
//#import "YBImageBrowser.h"
#import "RCloudImageView.h"
//预览-->防截屏处理
#import "NSChatPhotoBrowser.h"
#import "GKPhotoBrowser.h"
//pop
#import "NSPPPopView.h"
#import "NSPVPopView.h"
#import "NSVipPopView.h"

#import "NSMatchViewController.h"
#import "NSFlashChatViewController.h"
@interface NSConversationViewController ()
<
UICollectionViewDelegate,
UICollectionViewDataSource,
RCIMReceiveMessageDelegate,
RCMessageExpansionDelegate,
UIImagePickerControllerDelegate
>
@property (nonatomic, strong) UIImageView *backImageView;
@property (nonatomic, strong) NSConversitionNavView *conversitionNavView;
@property (nonatomic, strong) UILabel *placeLab;
@property (nonatomic, strong) UIButton *imageSelectBtn;
@property (nonatomic, strong) UIButton *emojiSelectBtn;

@property (nonatomic, strong) UIButton *sendMessageBtn;
//
@property (nonatomic, strong) UIView *secView;
//已成功发送的次数
@property (nonatomic, assign) NSInteger sendedNum;
//是否发过信息
@property (nonatomic, assign) BOOL isSended;
//matched 表头
@property (nonatomic, strong) NSMatchHeaderView *matchHeaderView;
//预览数组
@property (nonatomic, strong) NSMutableArray *dataArr;
//pop
@property (nonatomic, strong) NSPPPopView *ppPopView;
@property (nonatomic, strong) NSPVPopView *pvPopView;
@property (nonatomic, strong) NSVipPopView *vipPopView;
@end

@implementation NSConversationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = HEXS(@"22253C");
    [self setupUI];
    //键盘设置
    [IQKeyboardManager sharedManager].enable = NO;
    //融云代理
    [RCIM sharedRCIM].receiveMessageDelegate = self;
    [RCIMClient sharedRCIMClient].messageExpansionDelegate = self;
    RCKitConfigCenter.message.enabledReadReceiptConversationTypeList = nil;
    self.displayUserNameInCell = NO;
    
    //作用-->获得可聊天次数和matched 标识
//    if (![MBUserAccount defaultAccount].isVip) {
        [self getUserMessageNum];
//    }
    
    //
//    [RCCoreClient sharedCoreClient].imageCompressConfig.maxSize = 149;
//    [RCCoreClient sharedCoreClient].imageCompressConfig.minSize = 112;
    
    //截屏事件监听
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(screenshots) name:UIApplicationUserDidTakeScreenshotNotification  object:nil];
    //录屏事件监听
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(screenrecording) name:UIScreenCapturedDidChangeNotification  object:nil];
    if (self.isFlashChat) {
        [self sendFlashChat];
    }
    
    if (!self.isFromList) {
        [self getRCUserInfo];
    }
    
    NSMutableArray *marr = [[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
    for (BaseViewController *vc in marr) {
        if ([vc isKindOfClass:[NSMatchViewController class]] || [vc isKindOfClass:[NSFlashChatViewController class]]) {
            [marr removeObject:vc];
            break;
        }
    }
    self.navigationController.viewControllers = marr;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.chatSessionInputBarControl.inputTextView.text = nil;
    //页面即将消失---离开此页面 刷新全局消息未读数
    MBUserAccount  *account = [MBUserAccount defaultAccount];
    [[RCCoreClient sharedCoreClient] getTotalUnreadCountWith:^(int unreadCount) {
        [[RCCoreClient sharedCoreClient] getUnreadCount:ConversationType_PRIVATE targetId:[MBUserAccount defaultAccount].kefuTargetId completion:^(int count) {
            dispatch_async(dispatch_get_main_queue(), ^{
                account.unReadNum = unreadCount-count;
                [MBUserAccount  saveAccount:account];
                [[NSNotificationCenter defaultCenter] postNotificationName:UPDATE_MESSAGE_UNREAD object:nil];
            });
        }];
    }];
    
    if (![MBUserAccount defaultAccount].isVip) {
        [[MBChatDataManager sharedManager] getUserMessageNumWithUserCode:self.targetId type:2 success:^(BOOL success) {
        }];
    }
    
    //注销cell定时器
    // 停止定时器
//    for (int i = 0; i<self.conversationMessageCollectionView.visibleCells.count; i++) {
//        if ([self.conversationMessageCollectionView.visibleCells[i] isKindOfClass:[RCImageMessageCell class]]) {
//            RCImageMessageCell *cell1 = self.conversationMessageCollectionView.visibleCells[i];
//            for (NSModelHotView *view in cell1.messageContentView.subviews) {
//                [view stopTimer];
//            }
//        } else if ([self.conversationMessageCollectionView.visibleCells[i] isKindOfClass:[RCSightMessageCell class]]) {
//            RCSightMessageCell *cell1 = self.conversationMessageCollectionView.visibleCells[i];
//            for (NSModelHotView *view in cell1.messageContentView.subviews) {
//                [view stopTimer];
//            }
//        }
//    }
//    [self.conversationMessageCollectionView.visibleCells enumerateObjectsUsingBlock:^(RCMessageBaseCell *cell, NSUInteger idx, BOOL *stop) {
//        if ([cell isKindOfClass:[RCImageMessage class]]) {
//            RCImageMessageCell *cell1 = (RCImageMessageCell *)cell;
//            for (UIView *view in cell1.messageContentView.subviews) {
//                if ([view isKindOfClass:[NSModelHotView class]]) {
//                    NSModelHotView *view0 = (NSModelHotView *)view;
//                    [view0 stopTimer];
//                }
//            }
//        } else if ([cell isKindOfClass:[RCSightMessageCell class]]) {
//            RCSightMessageCell *cell1 = (RCSightMessageCell *)cell;
//            for (UIView *view in cell1.messageContentView.subviews) {
//                if ([view isKindOfClass:[NSModelHotView class]]) {
//                    NSModelHotView *view0 = (NSModelHotView *)view;
//                    [view0 stopTimer];
//                }
//            }
//        }
//    }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //安卓端发来的视频没有缩略图,在此处加载缩略图并缓存和刷新
    for (int i = 0; i<self.conversationDataRepository.count; i++) {
        RCMessageModel *model = [self.conversationDataRepository objectAtIndex:i];
        if ([model.objectName isEqualToString:@"RC:SightMsg"]) {
            RCSightMessage *message = (RCSightMessage*)model.content;
            if (message.thumbnailImage == nil) {
//                UIImage *image = [[MBThumbnailCache sharedCache] getThumbnailImageForKey:message.remoteUrl];
                [self loadAndSaveImage:message index:i];
            }
        }
    }
    
//    [NSTimer scheduledTimerWithTimeInterval:1
//                                     target:self
//                                   selector:@selector(timeChanged:)
//                                   userInfo:nil
//                                    repeats:YES];
}

- (void)loadAndSaveImage:(RCSightMessage *)message index:(NSInteger)index {
    dispatch_queue_t queue = dispatch_queue_create("meboo", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_async(queue, ^{
        UIImage *image = [[MBThumbnailCache sharedCache] getThumbnailImageForKey:message.remoteUrl];
        if (image == nil) {
            image = [[MBThumbnailCache sharedCache] getThumbnailImage:message.remoteUrl];
            [[MBThumbnailCache sharedCache] setThumbnailImage:image forKey:message.remoteUrl];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.conversationMessageCollectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]]];
            });
        }
    });
    

}

- (void)timeChanged:(NSTimer *)timer {
    [self.conversationMessageCollectionView reloadData];
}

/**
 方法作用: 根据id获取融云信息 主要包括model和自身的头像名称等信息
 注意事项: list页面进来,已经处理过无需再加载,其他页面进入,需要执行加载
 */
- (void)getRCUserInfo {
    __WeakSelf
    //创建调度组和并发队列
    dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t group = dispatch_group_create();
    
    //model信息加载
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        [[MBChatDataManager sharedManager] getUserInfoWithUserId:self.targetId completion:^(RCUserInfo * _Nonnull userInfo) {
            [[RCIM sharedRCIM] refreshUserInfoCache:userInfo withUserId:self.targetId];
            dispatch_group_leave(group);
        }];
    });
    //用户个人信息加载
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        [[MBChatDataManager sharedManager] getUserInfoWithUserId:[MBUserAccount defaultAccount].chatUserId completion:^(RCUserInfo * _Nonnull userInfo) {
            [[RCIM sharedRCIM] refreshUserInfoCache:userInfo withUserId:[MBUserAccount defaultAccount].chatUserId];
            dispatch_group_leave(group);
        }];
    });
    
    //任务完成统一回调-->回到主线程刷新UI
    dispatch_group_notify(group, queue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.conversationMessageCollectionView reloadData];
        });
    });
}

//实例化后一些必要参数的加载和赋值
- (void)setIsSayHi:(BOOL)isSayHi {
    _isSayHi = isSayHi;
}

- (void)setIsFlashChat:(BOOL)isFlashChat {
    _isFlashChat = isFlashChat;
}

- (void)setIsFromWLM:(BOOL)isFromWLM {
    _isFromWLM = isFromWLM;
}

- (void)setIsFromList:(BOOL)isFromList {
    _isFromList = isFromList;
}

/**
 将match页面选择的emoji或者输入文本传过来并发送消息
 */
- (void)setMatchedStr:(NSString *)matchedStr {
    _matchedStr = matchedStr;
    __WeakSelf
    RCTextMessage *messageContent = [RCTextMessage messageWithContent:matchedStr];
    RCMessage *message = [[RCMessage alloc]
                          initWithType:ConversationType_PRIVATE
                          targetId:self.targetId
                          direction:MessageDirection_SEND
                          content:messageContent];
    [[RCIM sharedRCIM]
     sendMessage:message
     pushContent:nil
     pushData:nil
     successBlock:^(RCMessage *successMessage) {
        //成功
        weakSelf.sendedNum++;
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.chatSessionInputBarControl.inputTextView.text = nil;
        });
    }
     errorBlock:^(RCErrorCode nErrorCode, RCMessage *errorMessage) {
        //失败
    }];
}

//重写pop返回事件,用以确定block的调用
- (void)didMoveToParentViewController:(UIViewController *)parent {
    [super didMoveToParentViewController:parent];
    if (self.sendedNum > 0 && self.sendMessageBlock && ![MBUserAccount defaultAccount].isVip) {
        self.sendMessageBlock(self.sendedNum);
    }
    
    if (self.isFromWLM && self.isSended) {
        [MBNotificationCenter postNotificationName:WLM_CHAT_SENDED object:nil];
    }
}

#pragma mark - Private Method
//截屏警告
- (void)screenshots {
    [MBProgressHUD showWarnMessage:@"No screenshot allowed."];
}
//录屏警告
- (void)screenrecording {
    if ([UIScreen mainScreen].isCaptured) {
        [MBProgressHUD showWarnMessage:@"No screen recording allowed."];
    }
}

//获取用户免费聊天次数 和matched 状态
- (void)getUserMessageNum {
    [[MBChatDataManager sharedManager] getUserMessageNumWithUserCode:self.targetId type:1 success:^(BOOL success) {
        if (success && [MBChatDataManager sharedManager].isMatched) {
            self.isMatched = YES;
            [self.conversationMessageCollectionView reloadData];
        }
    }];
}

- (void)setNavTitle {
    RCUserInfo *userInfo = [[RCIM sharedRCIM] getUserInfoCache:self.targetId];
    if (userInfo.name.length > 0) {
        self.conversitionNavView.nameStr = userInfo.name;
        if ([self.conversitionNavView.nameStr isEqualToString:@"user<>"]) {
            self.conversitionNavView.nameStr = @"Meboo";
        }
    } else {
        [[MBChatDataManager sharedManager] getUserInfoWithUserId:self.targetId completion:^(RCUserInfo * _Nonnull userInfo) {
            self.conversitionNavView.nameStr = userInfo.name;
            if ([self.conversitionNavView.nameStr isEqualToString:@"user<>"]) {
                self.conversitionNavView.nameStr = @"Meboo";
            }
            [[RCIM sharedRCIM] refreshUserInfoCache:userInfo withUserId:self.targetId];
        }];
    }
}

#pragma mark - Public Method

- (void)messageExpansionDidUpdate:(NSDictionary<NSString *, NSString *> *)expansionDic
                          message:(RCMessage *)message {
    dispatch_async(dispatch_get_main_queue(), ^{
        for (int i = 0; i<self.conversationDataRepository.count; i++) {
            RCMessageModel *model = self.conversationDataRepository[i];
            if (model.messageId == message.messageId) {
                RCMessageModel *model0 = [RCMessageModel modelWithMessage:message];
                [self.conversationDataRepository replaceObjectAtIndex:i withObject:model0];
                [self.conversationMessageCollectionView reloadData];
                break;
            }
        }
    });
}

- (void)onRCIMReceiveMessage:(RCMessage *)message left:(int)left {
    if ([message.targetId isEqualToString:self.targetId]) {
        RCMessageModel *model = [RCMessageModel modelWithMessage:message];
        [self.conversationDataRepository addObject:model];
        __WeakSelf
        if (left == 0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.conversationMessageCollectionView reloadData];
                [weakSelf scrollToBottomAnimated:YES];
            });
        }
    }
}

- (BOOL)onRCIMCustomLocalNotification:(RCMessage *)message withSenderName:(NSString *)senderName {
    NSLog(@"");
    return NO;
}

- (BOOL)onRCIMCustomAlertSound:(RCMessage *)message {
    NSLog(@"");
    return NO;
}

#pragma mark - Action

#pragma mark - 消息发送
- (void)sendMessageAction {
    //首先判断是否会员
    //非会员判断 免费次数
    if ([MBUserAccount defaultAccount].isVip) {
        
    } else {
        if (self.sendedNum >= [MBChatDataManager sharedManager].messagesNumber) {
            //非会员,免费用完了,跳转VIP
            self.vipPopView.index = 0;
            [self.view addSubview:self.vipPopView];
            self.vipPopView.hidden = NO;
            [self.view endEditing:YES];
            return;
        }
    }
    
    if (self.chatSessionInputBarControl.inputTextView.text.length == 0) {
        return;
    }
    __WeakSelf
    RCTextMessage *messageContent = [RCTextMessage messageWithContent:self.chatSessionInputBarControl.inputTextView.text];
    
    RCMessage *message = [[RCMessage alloc]
                          initWithType:ConversationType_PRIVATE
                          targetId:self.targetId
                          direction:MessageDirection_SEND
                          content:messageContent];
    
    
    [[RCIM sharedRCIM]
     sendMessage:message
     pushContent:nil
     pushData:nil
     successBlock:^(RCMessage *successMessage) {
        weakSelf.isSended = YES;
        //成功
        weakSelf.sendedNum++;
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.chatSessionInputBarControl.inputTextView.text = nil;
        });
        
        if (weakSelf.sendedNum > 1) {
            /**
             埋点 code
             破冰会话 306
             */
            [[NSIOApiManager sharedManager] setIOWithCode:@"306" content:@"PURCHASE_FIRST_CHAT"];
        }
        
        if (weakSelf.sendedNum > 5) {
            /**
             埋点 code
             有效会话 307
             */
            [[NSIOApiManager sharedManager] setIOWithCode:@"307" content:@"PURCHASE_EFFECTIVE_CHAT"];
        }
        
        if (weakSelf.sendedNum > 30) {
            /**
             埋点 code
             深度会话 308
             */
            [[NSIOApiManager sharedManager] setIOWithCode:@"308" content:@"PURCHASE_DEEP_CHAT"];
        }
    }
     errorBlock:^(RCErrorCode nErrorCode, RCMessage *errorMessage) {
        //失败
    }];
    
}

- (void)sendFlashChat {
    __WeakSelf
    RCTextMessage *messageContent = [RCTextMessage messageWithContent:@"Hi there! Let's make this app less boring together"];
    
    RCMessage *message = [[RCMessage alloc]
                          initWithType:ConversationType_PRIVATE
                          targetId:self.targetId
                          direction:MessageDirection_SEND
                          content:messageContent];
    
    
    [[RCIM sharedRCIM]
     sendMessage:message
     pushContent:nil
     pushData:nil
     successBlock:^(RCMessage *successMessage) {
        //成功
        weakSelf.sendedNum++;
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.chatSessionInputBarControl.inputTextView.text = nil;
        });
    }
     errorBlock:^(RCErrorCode nErrorCode, RCMessage *errorMessage) {
        //失败
    }];
}

- (void)imageSelectAction {
//    [self uploadImg];
    NSPhotoViewController *photoViewController = [NSPhotoViewController new];
    photoViewController.targetId = self.targetId;
    [self.navigationController pushViewController:photoViewController animated:YES];
    
    //保证滚动到底部
    [self.conversationMessageCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.conversationDataRepository.count-1 >= 0 ? self.conversationDataRepository.count-1 : 0 inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:NO];
    
    /**
     埋点
     点击相册Chat_Album
     */
    [[NSIOApiManager sharedManager] setIOWithEventName:@"Chat_Album"];
}
//cell1.pictureView.contentMode = UIViewContentModeScaleAspectFill;


#pragma mark -- collectionView  delegate datasource
- (void)willDisplayMessageCell:(RCMessageBaseCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    RCMessageCell *messageCell = (RCMessageCell *)cell;
    messageCell.portraitImageView.contentMode = UIViewContentModeScaleAspectFill;
    
    __WeakSelf
    RCMessageModel *model = [self.conversationDataRepository objectAtIndex:indexPath.row];
    BOOL isPrivate = [model.expansionDic[@"isPrivate"] boolValue];
    NSInteger second = 0;
    NSString *destructTime = model.expansionDic[@"destructTime"];
    if (destructTime.length > 0) {
        second = [self getHotSecondWith:destructTime];
    }
    
    if (model.conversationType == ConversationType_PRIVATE) {
        if (model.content && (model.sentStatus == SentStatus_READ ||model.sentStatus == SentStatus_SENT) && model.messageDirection == MessageDirection_SEND) {
            for (UIView *view in [((RCMessageCell *)cell).statusContentView subviews]) {
                [view removeFromSuperview];
            }
        }else{
            UIView *tagView = [((RCMessageCell *)cell).statusContentView viewWithTag:1001];
            if (tagView) {
                [tagView removeFromSuperview];
            }
        }
    }
    
    //&& model.messageDirection == MessageDirection_RECEIVE
    if ([model.objectName isEqualToString:@"RC:ImgMsg"]) {
        RCImageMessage *message = (RCImageMessage*)model.content;
        RCImageMessageCell *cell1 = (RCImageMessageCell *)cell;
        cell1.pictureView.hidden = YES;
        cell1.pictureView.contentMode = UIViewContentModeScaleAspectFill;
        for (UIView *view in cell1.messageContentView.subviews) {
            if ([view isKindOfClass:[UIVisualEffectView class]]) {
                [view removeFromSuperview];
            }
            if (view.tag >= 2000) {
                [view removeFromSuperview];
            }
        }

        
        NSModelHotView *hotView = [NSModelHotView new];
        hotView.timeEndBlock = ^{
            [weakSelf.conversationMessageCollectionView reloadData];
        };
        hotView.tag = 2000;
        hotView.frame = cell1.messageContentView.bounds;
        
        if (message.thumbnailImage == nil) {
            [cell1.pictureView sd_setImageWithURL:[NSURL URLWithString:message.imageUrl]];
            cell1.pictureView.contentMode = UIViewContentModeScaleAspectFill;
//            cell1.pictureView.frame = CGRectMake(cell1.pictureView.frame.origin.x, cell1.pictureView.frame.origin.y, 112, 149);
            
//            cell1.messageContentView.frame = CGRectMake(cell1.messageContentView.frame.origin.x, cell1.messageContentView.frame.origin.y, 112, 149);
            
            UIBezierPath *maskPath;
                cell1.messageContentView.backgroundColor = UIColor.clearColor;
                maskPath = [UIBezierPath bezierPathWithRoundedRect:cell1.messageContentView.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerBottomLeft | UIRectCornerTopRight | UIRectCornerBottomRight) cornerRadii:CGSizeMake(MBHeightScale(12),MBHeightScale(12))];//圆角大小
            CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
            maskLayer.frame = cell1.messageContentView.bounds;
            maskLayer.path = maskPath.CGPath;
            cell1.messageContentView.layer.mask = maskLayer;
        }
        
        
        if (isPrivate) {
            //加密
            if (destructTime.length > 0) {
                //已解锁
                if (second > 0) {
                    //有效期倒计时
                    hotView.second = second;
                    [cell1.messageContentView  addSubview:hotView];
                    cell1.pictureView.hidden = NO;
                } else {
                    //过期了
                    cell1.pictureView.hidden = YES;
                    if (message.thumbnailImage == nil) {
                        [self getImage:message.imageUrl photo:nil imageView:cell1.pictureView];
                    } else {
                        [self getImage:@"" photo:message.thumbnailImage imageView:cell1.pictureView];
                    }
                    UILabel *destructLab = [UILabel new];
                    destructLab.numberOfLines = 2;
                    destructLab.textAlignment = NSTextAlignmentCenter;
                    destructLab.text = @"Image Has\nExpired";
                    destructLab.font = MBHelFontSizeScale(14);
                    destructLab.textColor = UIColor.whiteColor;
                    destructLab.tag = 2001;
                    [cell1.messageContentView  addSubview:destructLab];
                    [destructLab mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.center.equalTo(cell1.messageContentView);
                    }];
                }
            } else {
                //未解锁
                cell1.pictureView.hidden = YES;
                if (message.thumbnailImage == nil) {
                    [self getImage:message.imageUrl photo:nil imageView:cell1.pictureView];
                } else {
                    [self getImage:@"" photo:message.thumbnailImage imageView:cell1.pictureView];
                }
                hotView.playImageView.image = ImageWithName(@"chat_image_recive_secret");
                hotView.playImageView.hidden = NO;
                [cell1.messageContentView  addSubview:hotView];
            }
        } else {
            //未加密
            [cell1.messageContentView  addSubview:hotView];
            cell1.pictureView.hidden = NO;
        }
        return;
    }
    // && model.messageDirection == MessageDirection_RECEIVE
    else if ([model.objectName isEqualToString:@"RC:SightMsg"]) {
        RCSightMessage *message = (RCSightMessage*)model.content;
        RCSightMessageCell *cell1 = (RCSightMessageCell *)cell;
        cell1.thumbnailView.contentMode = UIViewContentModeScaleAspectFill;
        
        for (UIView *view in cell1.messageContentView.subviews) {
            if ([view isKindOfClass:[UIVisualEffectView class]]) {
                [view removeFromSuperview];
            }
            
            if (view.tag >= 2000) {
                [view removeFromSuperview];
            }
        }
    
        
        NSModelHotView *hotView = [NSModelHotView new];
        hotView.timeEndBlock = ^{
            [weakSelf.conversationMessageCollectionView reloadData];
        };
        hotView.tag = 2000;
        hotView.frame = cell1.messageContentView.bounds;
        
        UIImageView *thumbnailImage = [UIImageView new];
        if (message.thumbnailImage == nil) {
            RCMessageCell *cell1 = (RCMessageCell *)cell;
            cell1.nicknameLabel.hidden = YES;
            cell1.messageTimeLabel.text = [self cStringFromTimestamp:model.sentTime];
            
            thumbnailImage.tag = 3000;
            thumbnailImage.contentMode = UIViewContentModeScaleAspectFill;
            thumbnailImage.image = [[MBThumbnailCache sharedCache] getThumbnailImageForKey:message.remoteUrl];
            
            cell1.messageContentView.frame = CGRectMake(cell1.messageContentView.frame.origin.x, cell1.messageContentView.frame.origin.y, 112, 149);
            [cell1.messageContentView addSubview:thumbnailImage];
            [thumbnailImage mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(cell1.messageContentView);
            }];
                        
            UIBezierPath *maskPath;
                cell1.messageContentView.backgroundColor = UIColor.clearColor;
                maskPath = [UIBezierPath bezierPathWithRoundedRect:cell1.messageContentView.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerBottomLeft | UIRectCornerTopRight | UIRectCornerBottomRight) cornerRadii:CGSizeMake(MBHeightScale(12),MBHeightScale(12))];//圆角大小
            CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
            maskLayer.frame = cell1.messageContentView.bounds;
            maskLayer.path = maskPath.CGPath;
            cell1.messageContentView.layer.mask = maskLayer;
            if (![[MBThumbnailCache sharedCache] getThumbnailImageForKey:message.remoteUrl]) {
                [self loadAndSaveImage:message index:indexPath.row];
            }
        }
        
        if (isPrivate) {
            //加密
            if (destructTime.length > 0) {
                //已解锁
                if (second > 0) {
                    //有效期倒计时
                    hotView.second = second;
                    hotView.videoLength = message.duration;
                    [cell1.messageContentView  addSubview:hotView];
                } else {
                    //过期了
                    cell1.thumbnailView.hidden = YES;
                    
                    if (message.thumbnailImage == nil) {
                        [self getImage:nil photo:thumbnailImage.image imageView:thumbnailImage];
                    } else {
                        [self getImage:nil photo:message.thumbnailImage imageView:cell1.thumbnailView];
                    }
                    UILabel *destructLab = [UILabel new];
                    destructLab.numberOfLines = 2;
                    destructLab.textAlignment = NSTextAlignmentCenter;
                    destructLab.text = @"Video Has\nExpired";
                    destructLab.font = MBHelFontSizeScale(14);
                    destructLab.textColor = UIColor.whiteColor;
                    destructLab.tag = 2001;
                    [cell1.messageContentView  addSubview:destructLab];
                    [destructLab mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.center.equalTo(cell1.messageContentView);
                    }];
                }
            } else {
                //未解锁
                cell1.thumbnailView.hidden = YES;
                if (message.thumbnailImage == nil) {
                    [self getImage:nil photo:thumbnailImage.image imageView:thumbnailImage];
                } else {
                    [self getImage:nil photo:message.thumbnailImage imageView:cell1.thumbnailView];
                }
                hotView.playImageView.image = ImageWithName(@"chat_image_recive_secret");
                hotView.videoLength = message.duration;
                [cell1.messageContentView  addSubview:hotView];
            }
        } else {
            //未加密
            hotView.videoLength = message.duration;
            [cell1.messageContentView  addSubview:hotView];
        }
        return;
    }
    
    if ([model.objectName isEqualToString:@"RC:TxtMsg"]) {
        RCMessageCell *cell1 = (RCMessageCell *)cell;
        UIImageView *backImageView = cell1.messageContentView.subviews[0];
        RCAttributedLabel *backLab = cell1.messageContentView.subviews[2];
//        backLab.font = PDRegularScale(15);
        backLab.font = [UIFont fontWithName:@"PlayfairDisplay-Regular" size:15];
        if (cell1.messageDirection == MessageDirection_SEND) {
            backLab.textColor = HEXS(@"ffffff");
        } else {
            backLab.textColor = HEXS(@"000000");
        }
        backImageView.hidden = YES;
    }
    
    RCMessageCell *cell1 = (RCMessageCell *)cell;
    cell1.messageTimeLabel.text = [self cStringFromTimestamp:model.sentTime];
    cell1.nicknameLabel.hidden = YES;
    cell1.contentView.backgroundColor = UIColor.clearColor;
    UIBezierPath *maskPath;
    if (cell1.messageDirection == MessageDirection_SEND) {
        cell1.messageContentView.backgroundColor = HEXS(@"B92176");
        maskPath = [UIBezierPath bezierPathWithRoundedRect:cell1.messageContentView.bounds byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerTopLeft | UIRectCornerBottomRight) cornerRadii:CGSizeMake(MBHeightScale(12),MBHeightScale(12))];//圆角大小
    } else {
        cell1.messageContentView.backgroundColor = UIColor.whiteColor;
        maskPath = [UIBezierPath bezierPathWithRoundedRect:cell1.messageContentView.bounds byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerTopRight | UIRectCornerBottomRight) cornerRadii:CGSizeMake(MBHeightScale(12),MBHeightScale(12))];//圆角大小
    }
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = cell1.messageContentView.bounds;
    maskLayer.path = maskPath.CGPath;
    cell1.messageContentView.layer.mask = maskLayer;
}

- (void)getImage:(NSString *)urlStr photo:(UIImage *)photo imageView:(UIImageView *)imageView {
    if (urlStr.length > 0) {
        [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:urlStr] options:SDWebImageRetryFailed progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            imageView.image = [image blurredImageWithRadius:BlurValue iterations:2 tintColor:HEXS(@"000000")];
            imageView.hidden = NO;
        }];
    } else {
        imageView.image = [photo blurredImageWithRadius:BlurValue iterations:2 tintColor:HEXS(@"000000")];
        imageView.hidden = NO;
    }
}

//定义每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
//    RCMessageModel *model = [self.conversationDataRepository objectAtIndex:indexPath.row];
//    if ([model.objectName isEqualToString:@"RC:ImgMsg"] && model.messageDirection == MessageDirection_RECEIVE) {
//        RCImageMessage *message = (RCImageMessage*)model.content;
//        if (message.thumbnailImage == nil) {
//            return CGSizeMake(ScreenWidth, MBHeightScale(180));
//        }
//    }
//    if ([model.objectName isEqualToString:@"RC:SightMsg"] && model.messageDirection == MessageDirection_RECEIVE) {
//        RCSightMessage *message = (RCSightMessage*)model.content;
//        if (message.thumbnailImage == nil) {
//            return CGSizeMake(ScreenWidth, MBHeightScale(180));
//        }
//    }
    
    
//    return CGSizeMake(MBWidthScale(162), MBHeightScale(152));
    return [super collectionView:collectionView layout:collectionViewLayout sizeForItemAtIndexPath:indexPath];
    
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (self.isFromWLM || self.isMatched) {
        if([kind isEqualToString:UICollectionElementKindSectionHeader]) {
            NSMatchHeaderView *reviewHeadView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"NSMatchHeaderView" forIndexPath:indexPath];
            RCUserInfo *userInfo = [[RCIM sharedRCIM] getUserInfoCache:self.targetId];
            [reviewHeadView.modelImageView sd_setImageWithURL:[NSURL URLWithString:userInfo.portraitUri]];
            return reviewHeadView;
        }
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (self.isFromWLM || self.isMatched) {
        return CGSizeMake(ScreenWidth, MBHeightScale(158));
    } else {
        return CGSizeMake(0, 0);
    }
}

// 时间戳—>字符串时间
- (NSString *)cStringFromTimestamp:(long long)timestamp {
    timestamp = timestamp/1000;
    //时间戳转时间的方法
    NSDate *timeData = [NSDate dateWithTimeIntervalSince1970:timestamp];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm"];
    NSString *strTime = [dateFormatter stringFromDate:timeData];
    NSCalendar *calendar = [NSCalendar currentCalendar];//定义一个NSCalendar对象
    
    if ([calendar isDateInToday:timeData]) {
        //是否是今天
        return strTime;
    } else if ([calendar isDateInYesterday:timeData]) {
        //是否是昨天
        return @"Yesterday";
    } else {
        [dateFormatter setDateFormat:@"MM/dd"];
        return [dateFormatter stringFromDate:timeData];
    }
}

- (NSString *)getTimeNow {
    //毫秒的时间戳
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这个对于时间的处理有时很重要
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    return timeSp;
}

- (NSInteger)getHotSecondWith:(NSString *)destructTime {
    // 创建两个时间戳
    NSDate *timestamp1 = [NSDate dateWithTimeIntervalSince1970:[destructTime longLongValue]/1000]; // 第一个时间戳（2020-06-11 12:00:00 UTC）
    NSDate *timestamp2 = [NSDate dateWithTimeIntervalSince1970:[[self getTimeNow] longLongValue]/1000]; // 第二个时间戳（2020-06-11 14:00:00 UTC）
    
    // 计算时间戳之间的差值
    NSTimeInterval timeInterval = [timestamp2 timeIntervalSinceDate:timestamp1];
    
    // 将差值转换为秒数
    NSInteger time = (NSInteger)timeInterval;
    
    
    
//    NSInteger time = [[self getTimeNow] longLongValue]-[destructTime longLongValue];
    time = 3600-time;
    time = time <= 0 ? 0 : time;
    return time;
}

/// 输入框中内容发生变化的回调
- (void)inputTextViewDidChange:(UITextView *)inputTextView {
    NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet];
    if ([[inputTextView.text stringByTrimmingCharactersInSet:set] length] == 0) {
        // 字符串全是空格
        self.sendMessageBtn.enabled = NO;
    } else {
        // 字符串不全是空格
        self.sendMessageBtn.enabled = YES;
    }
}

- (void)emojiView:(RCEmojiBoardView *)emojiView didTouchedEmoji:(NSString *)touchedEmoji {
    NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet];
    if ([[self.chatSessionInputBarControl.inputTextView.text stringByTrimmingCharactersInSet:set] length] == 0) {
        // 字符串全是空格
        self.sendMessageBtn.enabled = NO;
    } else {
        // 字符串不全是空格
        self.sendMessageBtn.enabled = YES;
    }
}

//文本内容点击键盘上的发送
- (void)inputTextViewDidTouchSendKey:(UITextView *)inputTextView {
    [self sendMessageAction];
}

//emoji点击键盘上的发送
- (void)emojiView:(RCEmojiBoardView *)emojiView didTouchSendButton:(UIButton *)sendButton {
    [self sendMessageAction];
}


- (void)uploadImg{
    __WeakSelf
    //获取
    UIAlertController  *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    if ([self getIsIpad]){
        alert.popoverPresentationController.sourceView = self.view;
        alert.popoverPresentationController.sourceRect = CGRectMake(ScreenWidth/2,ScreenHeight/2,0,0);
        alert.popoverPresentationController.permittedArrowDirections = 0;
    }
    
    UIAlertAction  *cameraAction = [UIAlertAction actionWithTitle:@"Camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];//读取设备授权状态
        if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
//            [SVProgressHUD showInfoWithStatus:RVString(@"CameraPermissions")];
        }else{
            //打开照相机
            if ([UIImagePickerController  isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIImagePickerController  *picker = [[UIImagePickerController alloc]init];
                picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, (NSString *)kUTTypeMovie, nil];
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                picker.allowsEditing = NO;
                picker.delegate = self;
                [self.currentViewController presentViewController:picker animated:YES completion:^{}];
            }
        }
    }];
    
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"Albums" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //从相册中获取图片
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.allowsEditing = NO;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, (NSString *)kUTTypeMovie, nil];
        picker.delegate = self;
        [self.currentViewController presentViewController:picker animated:YES completion:^{}];
    }];
    
    UIAlertAction  *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:photoAction];
    [alert  addAction:cameraAction];
    [alert addAction:cancelAction];
    [self.currentViewController presentViewController:alert animated:YES completion:nil];
}

//如果想要判断设备是ipad，要用如下方法
- (BOOL)getIsIpad {
    NSString *deviceType = [UIDevice currentDevice].model;
    
    if([deviceType isEqualToString:@"iPhone"]) {
        //iPhone
        return NO;
    }
    else if([deviceType isEqualToString:@"iPod touch"]) {
        //iPod Touch
        return NO;
    }
    else if([deviceType isEqualToString:@"iPad"]) {
        //iPad
        return YES;
    }
    return NO;
}


#pragma mark - UIImagePickerControllerDelegate

-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    __WeakSelf
    ChatSelectImageViewController *headVC = [[ChatSelectImageViewController alloc]init];
    headVC.targetId = self.targetId;
    UIImage *editedImage = info[UIImagePickerControllerOriginalImage];
    if (editedImage) {
        //图片
        headVC.oldImage = editedImage;
    } else {
        //视频
        headVC.videoUrl = info[UIImagePickerControllerMediaURL];
    }
    [weakSelf.currentViewController.navigationController pushViewController:headVC animated:YES];
}

#pragma mark -- delegate 消息处理的回调
//点击消息 Cell 头像
- (void)didTapCellPortrait:(NSString *)userId {
    if ([userId isEqualToString:[MBUserAccount defaultAccount].chatUserId]) {
        return;
    }
    NSModelDetailViewController *modelDetailVc = [NSModelDetailViewController new];
    modelDetailVc.modelStyle = ChatModelDetail;
    modelDetailVc.userId = userId;
    [self.currentViewController.navigationController pushViewController:modelDetailVc animated:YES];
    /**
     埋点
     点击对方头像Chat_Avatar
     */
    [[NSIOApiManager sharedManager] setIOWithEventName:@"Chat_Avatar"];
}

//点击消息 Cell 中的 URL
- (void)didTapUrlInMessageCell:(NSString *)url model:(RCMessageModel *)model{
    NSLog(@"");
}

//点击消息 Cell 中的电话号码
- (void)didTapPhoneNumberInMessageCell:(NSString *)phoneNumber model:(RCMessageModel *)model{
    
}

- (void)didLongTouchMessageCell:(RCMessageModel *)model inView:(UIView *)view {
//    [super didLongTouchMessageCell:model inView:view];
}

#pragma mark - cell 点击事件
- (void)didTapMessageCell:(RCMessageModel *)model {
    //文本不处理
    if ([model.objectName isEqualToString:@"RC:TxtMsg"]) {
        return;
    }
    
    __WeakSelf
    //过期的私密不允许点击
    NSString *destructTime = model.expansionDic[@"destructTime"];
    if (destructTime.length > 0 && [self getHotSecondWith:destructTime] == 0) {
        return;
    }
    
    //有效期内的私密
    if (destructTime.length > 0 && [self getHotSecondWith:destructTime] > 0) {
        [self dealCommonModel:model];
        return;
    }
    
    //自己发的无需判断 直接预览
    if (model.messageDirection == MessageDirection_SEND) {
        [self dealCommonModel:model];
        return;
    }
    
    
    
    //imagecode
    NSString *imageCode = @"";
    NSData *data = [model.extra dataUsingEncoding:NSUTF8StringEncoding];
    if (data) {
        NSError *error = nil;
        id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
        if ([jsonObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
            // 在这里使用还原后的JSON字典
            imageCode = jsonDictionary[@"imageCode"];
        }
    }
    
    
    BOOL isPrivate = [model.expansionDic[@"isPrivate"] boolValue];
    if ([model.objectName isEqualToString:@"RC:ImgMsg"] && isPrivate) {
        RCImageMessage *message = (RCImageMessage*)model.content;
        //私密图片
        if ([MBUserAccount defaultAccount].ppNum > 0) {
            //有权益直接消费
            [MBProgressHUD showActivityMessageInWindow:@"Unlock Private Photos"];
            [[MBMineDataManager sharedManager] payWithType:2 chatUserCode:model.targetId msgId:[NSString stringWithFormat:@"%ld",model.messageId] imageCode:imageCode ?: message.imageUrl imageUrl:message.imageUrl success:^(BOOL success) {
                [MBProgressHUD hideHUD];
                if (success) {
                    [self pppvUpdateMessageInfo:model];
                    [MBProgressHUD showSuccessMessage:@"Unlock Success"];
                }
            }];
        }  else {
            //非会员先买会员才能买ppv
            if ([MBUserAccount defaultAccount].isVip) {
                //没有足够的ppv,弹出购买视图
                [self.view addSubview:self.ppPopView];
                self.ppPopView.hidden = NO;
                /**
                 埋点
                 私聊页点击pp拉起购买弹窗 Chat_PP_Buy
                 */
                [[NSIOApiManager sharedManager] setIOWithEventName:@"Chat_PP_Buy"];
            } else {
                [self.view addSubview:self.vipPopView];
                self.vipPopView.hidden = NO;
                self.vipPopView.index = 3;
                self.vipPopView.payBlock = ^{
                    //会员支付成功的回调
                    [weakSelf.view addSubview:weakSelf.ppPopView];
                    weakSelf.ppPopView.hidden = NO;
                    /**
                     埋点
                     解锁pp时是非会员状态 拉起会员订阅支付成功 Chat_PP_Subsuccess
                     */
                    [[NSIOApiManager sharedManager] setIOWithEventName:@"Chat_PP_Subsuccess"];
                };
                /**
                 埋点
                 解锁pp时是非会员状态 拉起会员订阅 Chat_PP_Sub
                 */
                [[NSIOApiManager sharedManager] setIOWithEventName:@"Chat_PP_Sub"];
            }
        }
        return;
    }
    
    if ([model.objectName isEqualToString:@"RC:SightMsg"] && isPrivate) {
        RCSightMessage *message = (RCSightMessage*)model.content;
        //私密视频
        if ([MBUserAccount defaultAccount].pvNum > 0) {
            //有权益直接消费
            [MBProgressHUD showActivityMessageInWindow:@"Unlock Private Videos"];
            [[MBMineDataManager sharedManager] payWithType:3 chatUserCode:model.targetId msgId:[NSString stringWithFormat:@"%ld",model.messageId] imageCode:imageCode ?: message.sightUrl imageUrl:message.sightUrl success:^(BOOL success) {
                [MBProgressHUD hideHUD];
                if (success) {
                    [self pppvUpdateMessageInfo:model];
                    [MBProgressHUD showSuccessMessage:@"Unlock Success"];
                }
            }];
        }  else {
            //非会员先买会员才能买ppv
            if ([MBUserAccount defaultAccount].isVip) {
                //没有足够的ppv,弹出购买视图
                [self.view addSubview:self.pvPopView];
                self.pvPopView.hidden = NO;
                /**
                 埋点
                 私聊页点击pv拉起购买弹窗 Chat_PV_Buy
                 */
                [[NSIOApiManager sharedManager] setIOWithEventName:@"Chat_PV_Buy"];
            } else {
                [self.view addSubview:self.vipPopView];
                self.vipPopView.hidden = NO;
                self.vipPopView.index = 4;
                self.vipPopView.payBlock = ^{
                    //会员支付成功的回调
                    [weakSelf.view addSubview:weakSelf.pvPopView];
                    weakSelf.pvPopView.hidden = NO;
                    
                    /**
                     埋点
                     解锁pv时是非会员状态 拉起会员订阅支付成功 Chat_PV_Subsuccess
                     */
                    [[NSIOApiManager sharedManager] setIOWithEventName:@"Chat_PV_Subsuccess"];
                };
                /**
                 埋点
                 解锁pv时是非会员状态  拉起会员订阅 Chat_PV_Sub
                 */
                [[NSIOApiManager sharedManager] setIOWithEventName:@"Chat_PV_Sub"];
            }
        }
        return;
    }
    
    [self dealCommonModel:model];
    
    //图片RC:ImgMsg 视频RC:SightMsg
//    if ([model.objectName isEqualToString:@"RC:SightMsg"]) {
//        MBChatPreviewVideoViewController *previewVc = [MBChatPreviewVideoViewController new];
//        RCSightMessage *sightMessage = (RCSightMessage *)model.content;
////        if (sightMessage.thumbnailImage == nil) {
//            previewVc.videoUrl = [NSURL URLWithString:sightMessage.sightUrl];
////        } else {
////            previewVc.videoUrl = [NSURL fileURLWithPath:sightMessage.localPath];
////        }
//        previewVc.modalPresentationStyle = UIModalPresentationFullScreen;
//        [self.navigationController presentViewController:previewVc animated:YES completion:nil];
//    } else {
//        [super didTapMessageCell:model];
//    }
}

//普通视频/图片/已解锁未过期的ppv
- (void)dealCommonModel:(RCMessageModel *)model {
    //埋点event
    NSString *ioStr = @"";
        
    //自定义预览-->防截屏
    [self.dataArr removeAllObjects];
    GKPhoto *preData = [GKPhoto new];
    if ([model.objectName isEqualToString:@"RC:ImgMsg"]) {
        RCImageMessage *message = (RCImageMessage*)model.content;
        preData.url = [NSURL URLWithString:message.imageUrl ? message.imageUrl : message.remoteUrl];
//        preData.placeholderImage =
        ioStr = @"Chat_Photo";
    } else if ([model.objectName isEqualToString:@"RC:SightMsg"]) {
        RCSightMessage *message = (RCSightMessage*)model.content;
        preData.videoUrl = [NSURL URLWithString:message.sightUrl ? message.sightUrl : message.remoteUrl];
        
        
//        YBIBVideoData *data2 = [YBIBVideoData new];
//        data2.videoURL = [NSURL URLWithString:message.sightUrl ? message.sightUrl : message.remoteUrl];
//        for (RCSightMessageCell *cell in self.conversationMessageCollectionView.visibleCells) {
//            if (cell.model.messageId == model.messageId) {
//                for (UIView *view in cell.messageContentView.subviews) {
//                    if (view.tag == 3000) {
//                        data2.projectiveView = view;
//                    } else {
//                        data2.projectiveView = cell.thumbnailView;
//                    }
//                }
//            }
//        }
//        YBImageBrowser *browser = [YBImageBrowser new];
//        browser.dataSourceArray = @[data2];
//        browser.currentPage = 0;
//        [browser show];
        
        
        ioStr = @"Chat_Video";
    }
    [self.dataArr addObject:preData];
    NSChatPhotoBrowser *browser = [NSChatPhotoBrowser photoBrowserWithPhotos:self.dataArr currentIndex:0];
    browser.showStyle = GKPhotoBrowserShowStyleZoom;
    browser.hideStyle = GKPhotoBrowserHideStyleZoomScale;
    browser.animDuration = 0.1;
    browser.hidesPageControl = YES;
    browser.hidesCountLabel = YES;
    [browser showFromVC:self];
    
    
    NSString *destructTime = model.expansionDic[@"destructTime"];
    //有效期内的私密
    if (destructTime.length > 0 && [self getHotSecondWith:destructTime] > 0) {
        if([model.objectName isEqualToString:@"RC:ImgMsg"]) {
            ioStr = @"Chat_PP";
        } else if ([model.objectName isEqualToString:@"RC:SightMsg"]) {
            ioStr = @"Chat_PV";
        }
    }
    
    /**
     埋点
     点击公开照片Chat_Photo
     点击公开视频Chat_Video
     点击私密照片Chat_PP
     点击私密视频Chat_PV
     */
    [[NSIOApiManager sharedManager] setIOWithEventName:ioStr];
}

- (void)pppvUpdateMessageInfo:(RCMessageModel *)model {
    __WeakSelf
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:model.expansionDic];
    [dict setObject:[NSString stringWithFormat:@"%@",[self getTimeNow]] forKey:@"destructTime"];
    model.expansionDic = dict;
    NSLog(@"");
    // 更新消息扩展信息
    [[RCCoreClient sharedCoreClient] updateMessageExpansion:dict messageUId:model.messageUId success:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.conversationMessageCollectionView reloadData];
        });
        // 更新发起者在这里处理更新扩展后的 UI 数据刷新
    } error:^(RCErrorCode status) {
    }];
}

- (UIView *)getBgView{
    UITextField *bgTextField = [[UITextField alloc] init];
    [bgTextField setSecureTextEntry:true];
    
    UIView *bgView = bgTextField.subviews.firstObject;
    [bgView setUserInteractionEnabled:true];
    bgView.backgroundColor = UIColor.clearColor;
    return bgView;
}

- (void)dealloc {
    [IQKeyboardManager sharedManager].enable = YES;
}

#pragma mark - UI
- (void)setupUI {
    
    for (UIView *view in self.view.subviews) {
        CGRect frame = view.frame;
        [view removeFromSuperview];
        [self.secView addSubview:view];
        view.frame = frame;
    }
    
    [self.view addSubview:self.secView];
    [self.view sendSubviewToBack:self.secView];
    [self.secView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.view addSubview:self.backImageView];
    [self.view sendSubviewToBack:self.backImageView];
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    
    [self.chatSessionInputBarControl setInputBarType:RCChatSessionInputBarControlDefaultType style:RC_CHAT_INPUT_BAR_STYLE_CONTAINER];
    self.chatSessionInputBarControl.inputContainerView.hideEmojiButton = YES;
    
    RCKitConfigCenter.ui.globalMessagePortraitSize = CGSizeMake(MBHeightScale(42), MBHeightScale(42));
    RCKitConfigCenter.ui.globalMessageAvatarStyle = RC_USER_AVATAR_CYCLE;
    //原sdk在最外层加了一层白色view,目的是为了保护底部安全区? 不得而知,暂时改颜色,如果没用后期可以移除.
    UIView *whiteView = self.secView.subviews[0];
    whiteView.backgroundColor = UIColor.clearColor;
//    [whiteView removeFromSuperview];
    
    //原sdk在chatSessionInputBarControl顶部有一条白线,不知何为,暂时改颜色,如果没用后期可以移除.
    CALayer *whiteLayer = self.chatSessionInputBarControl.layer.sublayers[1];
    whiteLayer.backgroundColor = UIColor.clearColor.CGColor;
    
    self.conversationMessageCollectionView.showsVerticalScrollIndicator = NO;
    self.conversationMessageCollectionView.backgroundColor = UIColor.clearColor;
    self.conversationMessageCollectionView.layer.cornerRadius = MBHeightScale(40);
//    self.conversationMessageCollectionView.contentInset = UIEdgeInsetsMake(MBHeightScale(158), 0, 0, 0);
    
    CGRect frame = self.conversationMessageCollectionView.frame;
    CGRect frame1;
    frame1 = CGRectMake(frame.origin.x, MBHeightScale(16)+StatusBarAndNavigationBarHeight, frame.size.width, 200);
    self.conversationMessageCollectionView.frame = frame1;


    
    self.chatSessionInputBarControl.backgroundColor = UIColor.clearColor;
    UIView *inputWhiteView = [UIView new];
    inputWhiteView.backgroundColor = UIColor.whiteColor;
    inputWhiteView.layer.cornerRadius = 20;
    [self.chatSessionInputBarControl addSubview:inputWhiteView];
    [self.chatSessionInputBarControl sendSubviewToBack:inputWhiteView];
    [inputWhiteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(MBWidthScale(12));
        make.right.mas_equalTo(MBWidthScale(-12));
        make.top.bottom.equalTo(self.chatSessionInputBarControl);
        if (TabbarSafeBottomMargin == 0) {
            make.bottom.mas_equalTo(MBHeightScale(-7));
        }
    }];
    
//    self.chatSessionInputBarControl.emojiButton
    self.chatSessionInputBarControl.inputTextView.backgroundColor = HEXS(@"ffffff");
    self.chatSessionInputBarControl.inputTextView.textColor = HEXS(@"333333");
    self.chatSessionInputBarControl.inputTextView.font = PDRegularScale(14);
    
    
//    [self.chatSessionInputBarControl.recordButton setImage:ImageWithName(@"chat_select_image") forState:0];
//    [self.chatSessionInputBarControl.recordButton addTarget:self action:@selector(imageSelectAction) forControlEvents:UIControlEventTouchUpInside];
//    [self.chatSessionInputBarControl.emojiButton setImage:ImageWithName(@"chat_send_message") forState:0];
//    [self.chatSessionInputBarControl.emojiButton addTarget:self action:@selector(sendMessageAction) forControlEvents:UIControlEventTouchUpInside];
        
    
    [self.chatSessionInputBarControl.inputTextView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
//        make.bottom.mas_equalTo(MBHeightScale(-38));
        make.left.mas_equalTo(MBWidthScale(95));
        make.height.mas_equalTo(MBHeightScale(40));
    }];
    
    [self.view addSubview:self.conversitionNavView];
    [self.conversitionNavView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(StatusBarAndNavigationBarHeight);
    }];
    
    [self.chatSessionInputBarControl.inputContainerView addSubview:self.imageSelectBtn];
    [self.imageSelectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(MBWidthScale(32));
        make.centerY.equalTo(self.chatSessionInputBarControl.inputTextView);
        make.height.mas_equalTo(MBHeightScale(20));
        make.width.mas_equalTo(MBHeightScale(20));
    }];
    self.imageSelectBtn.layer.cornerRadius = MBHeightScale(20);
    
    [self.chatSessionInputBarControl.inputContainerView addSubview:self.sendMessageBtn];
    [self.sendMessageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(MBWidthScale(-30));
        make.centerY.equalTo(self.imageSelectBtn);
        make.height.mas_equalTo(MBHeightScale(20));
        make.width.mas_equalTo(MBHeightScale(20));
    }];
    
    [self.emojiSelectBtn removeFromSuperview];
    [self.chatSessionInputBarControl.inputContainerView addSubview:self.emojiSelectBtn];
    [self.emojiSelectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.imageSelectBtn.mas_right).offset(MBWidthScale(15));
        make.centerY.equalTo(self.imageSelectBtn);
        make.height.mas_equalTo(MBHeightScale(20));
        make.width.mas_equalTo(MBHeightScale(20));
    }];
    
    self.chatSessionInputBarControl.inputTextView.toolbarPlaceholder = @"";
    [self.placeLab sizeToFit];
    [self.chatSessionInputBarControl.inputTextView addSubview:self.placeLab];
    [self.chatSessionInputBarControl.inputTextView setValue:self.placeLab forKey:@"_placeholderLabel"];
    
//    [self.conversationMessageCollectionView addSubview:self.matchHeaderView];
    [self.conversationMessageCollectionView  registerClass:[NSMatchHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"NSMatchHeaderView"];
    
    if ([self.targetId isEqualToString:[MBUserAccount defaultAccount].kefuTargetId]) {
        self.chatSessionInputBarControl.alpha = 0;
    } else {
        self.chatSessionInputBarControl.alpha = 1;
    }
    
    //头部组件
    [self setNavTitle];
    //test
//    [self.view addSubview:self.vipPopView];
    
    //pop
    [self vipPopView];
    [self ppPopView];
    [self pvPopView];
}

#pragma mark - Setter && Getter
- (NSConversitionNavView *)conversitionNavView {
    if (!_conversitionNavView) {
        _conversitionNavView = [NSConversitionNavView new];
        _conversitionNavView.userId = self.targetId;
//        __WeakSelf
        _conversitionNavView.conversitionBlock = ^{
//            NSConversationViewController *conversationVC = [[NSConversationViewController alloc] initWithConversationType:ConversationType_PRIVATE targetId:@""];
//            [weakSelf.navigationController pushViewController:conversationVC animated:YES];
        };
    }
    return _conversitionNavView;
}

- (UIButton *)imageSelectBtn {
    if (!_imageSelectBtn) {
        _imageSelectBtn = [[UIButton alloc] init];
        [_imageSelectBtn setYXEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
        [_imageSelectBtn setImage:ImageWithName(@"chat_select_image") forState:0];
        [_imageSelectBtn addTarget:self action:@selector(imageSelectAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _imageSelectBtn;
}

- (UIButton *)emojiSelectBtn {
    if (!_emojiSelectBtn) {
        _emojiSelectBtn = self.chatSessionInputBarControl.emojiButton;
        [_emojiSelectBtn setYXEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
        _emojiSelectBtn.hidden = NO;
        [_emojiSelectBtn setImage:ImageWithName(@"chat_select_emoji") forState:0];
    }
    return _emojiSelectBtn;
}

- (UIButton *)sendMessageBtn {
    if (!_sendMessageBtn) {
        _sendMessageBtn = [[UIButton alloc] init];
        [_sendMessageBtn setYXEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
        [_sendMessageBtn setImage:ImageWithName(@"chat_send_message") forState:0];
        [_sendMessageBtn addTarget:self action:@selector(sendMessageAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendMessageBtn;
}

- (UIView *)secView {
    if (!_secView) {
        _secView = [self getBgView];
    }
    return _secView;
}

- (UIImageView *)backImageView {
    if (!_backImageView) {
        _backImageView = [UIImageView new];
        _backImageView.image = ImageWithName(@"chat_back_image");
    }
    return _backImageView;
}

- (UILabel *)placeLab {
    if (!_placeLab) {
        _placeLab = [UILabel new];
        _placeLab.text = @"Your message...";
        _placeLab.textColor = HEXS(@"999999");
        _placeLab.font = PDRegularScale(14);
    }
    return _placeLab;
}

- (NSMatchHeaderView *)matchHeaderView {
    if (!_matchHeaderView) {
        _matchHeaderView = [[NSMatchHeaderView alloc] initWithFrame:CGRectMake(0, -MBHeightScale(158), ScreenWidth, MBHeightScale(158))];
    }
    return _matchHeaderView;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (NSPPPopView *)ppPopView {
    if (!_ppPopView) {
        _ppPopView = [[NSPPPopView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _ppPopView.payBlock = ^{
            /**
             埋点
             私聊页点击pp拉起购买弹窗支付成功 Chat_PP_Buysuccess
             */
            [[NSIOApiManager sharedManager] setIOWithEventName:@"Chat_PP_Buysuccess"];
        };
    }
    return _ppPopView;
}

- (NSPVPopView *)pvPopView {
    if (!_pvPopView) {
        _pvPopView = [[NSPVPopView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _pvPopView.payBlock = ^{
            /**
             埋点
             私聊页点击pv拉起购买弹窗支付成功 Chat_PV_Buysuccess
             */
            [[NSIOApiManager sharedManager] setIOWithEventName:@"Chat_PV_Buysuccess"];
        };
    }
    return _pvPopView;
}

- (NSVipPopView *)vipPopView {
    if (!_vipPopView) {
        _vipPopView = [[NSVipPopView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
//        _vipPopView.hidden = NO;
    }
    return _vipPopView;
}
@end
